package com.mission.schedule.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.mission.schedule.CommonDialog.NoteTypeNameEditDialog;
import com.mission.schedule.R;
import com.mission.schedule.adapter.NoteTypePXAdapter;
import com.mission.schedule.adapter.utils.CommonAdapter;
import com.mission.schedule.adapter.utils.ViewHolder;
import com.mission.schedule.annotation.ViewResId;
import com.mission.schedule.applcation.App;
import com.mission.schedule.bean.NoteTypeBean;
import com.mission.schedule.bean.TagCommandBean;
import com.mission.schedule.constants.ShareFile;
import com.mission.schedule.constants.URLConstants;
import com.mission.schedule.service.UpdataTagService;
import com.mission.schedule.utils.NetUtil;
import com.mission.schedule.utils.SharedPrefUtil;
import com.mobeta.android.dslv.DragSortListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class NoteTypepxActivity extends BaseActivity implements OnClickListener {

	@ViewResId(id = R.id.new_dtl_back)
	private LinearLayout new_dtl_back;
	@ViewResId(id = R.id.top_ll_right)
	private RelativeLayout top_ll_right;
	@ViewResId(id = R.id.tag_lv)
	private DragSortListView tag_lv;
	@ViewResId(id = R.id.myschedule_title)
	private TextView myschedule_title;

	Context context;

	App app = App.getDBcApplication();
	List<NoteTypeBean.ListBean> mList = new ArrayList<>();
	List<TagCommandBean> list = new ArrayList<TagCommandBean>();
	NoteTypePXAdapter adapter = null;
	String userid;
	SharedPrefUtil sharedPrefUtil = null;

	@Override
	protected void setListener() {
		new_dtl_back.setOnClickListener(this);
		top_ll_right.setOnClickListener(this);
	}
	int type = 0;
	CalenderTypePXAdapter calenderTypePXAdapter;

	@Override
	protected void setContentView() {
		setContentView(R.layout.qdpx);
	}

	@Override
	protected void init(Bundle savedInstanceState) {
		context = this;
		type = getIntent().getIntExtra("type",0);
		sharedPrefUtil = new SharedPrefUtil(context, ShareFile.USERFILE);
		userid = sharedPrefUtil.getString(context, ShareFile.USERFILE, ShareFile.USERID, "");
		tag_lv.setDropListener(onDrop);
		myschedule_title.setText("分类设置");
		// tag_lv.setRemoveListener(onRemove);
		loadData();
	}

	private void loadData() {
		if (type == 1) {
			mList = app.getAllNoteTypeData(userid, false);
			for (NoteTypeBean.ListBean bean : mList) {
				if (bean.content.equals("备忘录")) {
					mList.remove(bean);
					break;
				}
			}
			for (NoteTypeBean.ListBean bean : mList) {
				if (bean.content.equals("收到的")) {
					mList.remove(bean);
					break;
				}
			}
			adapter = new NoteTypePXAdapter(context, mList, handler, R.layout.adapter_qdpx);
			tag_lv.setAdapter(adapter);
			tag_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
					final List<NoteTypeBean.ListBean> listBeanList = adapter.mlList;
					NoteTypeNameEditDialog noteTypeNameEditDialog = new NoteTypeNameEditDialog(context, R.style.dialog_translucent,
							getWindowManager(), listBeanList.get(position).localId+"",listBeanList.get(position).content,type);
					noteTypeNameEditDialog.show();
					noteTypeNameEditDialog.setCallBack(new NoteTypeNameEditDialog.CallBack() {
						@Override
						public void updateTypeName(String name) {
							adapter.updateTypeName(name, position);
						}
					});
				}
			});
		} else {
			list = app.QueryTagData(11);
			calenderTypePXAdapter = new CalenderTypePXAdapter(context, list, handler, R.layout.adapter_qdpx);
			tag_lv.setAdapter(calenderTypePXAdapter);
			tag_lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
					final List<TagCommandBean> listBeanList = calenderTypePXAdapter.list;
					NoteTypeNameEditDialog noteTypeNameEditDialog = new NoteTypeNameEditDialog(context, R.style.dialog_translucent,
							getWindowManager(), listBeanList.get(position).ctgId,listBeanList.get(position).ctgText,type);
					noteTypeNameEditDialog.show();
					noteTypeNameEditDialog.setCallBack(new NoteTypeNameEditDialog.CallBack() {
						@Override
						public void updateTypeName(String name) {
							calenderTypePXAdapter.updateTypeName(name, position);
						}
					});
				}
			});
		}
	}

	@Override
	protected void setAdapter() {

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.new_dtl_back:
			this.finish();
			break;
		case R.id.top_ll_right:
			int i = 1;
			if (type == 1) {
				List<NoteTypeBean.ListBean> listBeanList = adapter.mlList;
				for (NoteTypeBean.ListBean bean : listBeanList) {
					int updatestate = app.getNoteTypestate(userid, bean.localId) == 0 ? 2 : 1;
					app.updateNoteTyeOrderId(i, bean.localId, userid, bean.content, updatestate);
					i++;
				}
			}else {
				List<TagCommandBean> tagCommandBeanList = calenderTypePXAdapter.list;
				for (TagCommandBean bean : tagCommandBeanList) {
					int updatestate = app.getCalenderTypestate(bean.ctgId) == 0 ? 2 : 1;
					app.updateClanderTyeOrderId(i, bean.ctgId, bean.ctgText, updatestate);
					i++;
				}
			}
			if (NetUtil.getConnectState(getApplication()) != NetUtil.NetWorkState.NONE) {
				if (sharedPrefUtil.getString(getApplication(),
						ShareFile.USERFILE, ShareFile.ISNEWYOUKE, "0").equals("-1")) {
					if (type == 1) {
						sysNoteType();
					}else {
						Intent intent = new Intent(getApplication(), UpdataTagService.class);
						intent.setAction("updateData");
						intent.putExtra("down", "upload");
						intent.setPackage(getPackageName());
						startService(intent);
					}
				}
			}else {
				Toast.makeText(context,"网络异常，无法进行同步操作",Toast.LENGTH_SHORT).show();
			}

			Intent intent = new Intent();
			setResult(Activity.RESULT_OK, intent);
			this.finish();
			break;
		default:
			break;
		}
	}

	private DragSortListView.DropListener onDrop = new DragSortListView.DropListener() {
		@Override
		public void drop(int from, int to) {
			if (from != to) {
				if (type == 1) {
					NoteTypeBean.ListBean item = adapter.getItem(from);
					adapter.remove(item);
					adapter.insert(item, to);
					adapter.notifyDataSetChanged();
				}else {
					TagCommandBean item = calenderTypePXAdapter.getItem(from);
					calenderTypePXAdapter.remove(item);
					calenderTypePXAdapter.insert(item, to);
					calenderTypePXAdapter.notifyDataSetChanged();
				}
			}
		}
	};

	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
		};
	};


	class CalenderTypePXAdapter extends CommonAdapter<TagCommandBean> {
		public List<TagCommandBean> list;
		private Handler handler;

		public CalenderTypePXAdapter(Context context, List<TagCommandBean> lDatas, Handler handler, int layoutItemID) {
			super(context, lDatas, layoutItemID);
			this.list = lDatas;
			this.handler = handler;
		}
		public void updateTypeName(String name,int position){
			list.get(position).setCtgText(name);
			notifyDataSetChanged();
		}

		@Override
		public void getViewItem(ViewHolder holder, TagCommandBean item, int position) {
			TextView content_tv = (TextView) holder.getView(R.id.content_tv);
			RelativeLayout tuodong_rl = (RelativeLayout) holder.getView(R.id.tuodong_rl);
			content_tv.setText(item.ctgText);
		}

		public void remove(TagCommandBean item) {
			if (item != null && list != null) {
				list.remove(item);
			}
		}

		public void insert(TagCommandBean item, int to) {
			if (item != null) {
				list.add(to, item);
			}
		}
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		super.onActivityResult(arg0, arg1, arg2);
		loadData();
		adapter.notifyDataSetChanged();
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	/**
	 * 清单分类同步
	 */
	public void sysNoteType(){
		final List<NoteTypeBean.ListBean> listBeanList = App.getDBcApplication().getAllNoteTypeData(userid,true);
		if (listBeanList.size() > 0) {
			JSONObject jsonObject = new JSONObject();
			try {
				JSONArray jsonArray = new JSONArray();
				for (NoteTypeBean.ListBean bean : listBeanList) {
					JSONObject object = new JSONObject();
					object.put("id", bean.id);
					object.put("orderId", bean.orderId);
					object.put("remark", bean.remark);
					object.put("remark1", bean.remark1);
					object.put("localId", bean.localId);
					object.put("changeTime", bean.changeTime);
					object.put("content", bean.content);
					object.put("styleId", bean.styleId);
					object.put("uid", bean.uid);
					object.put("updateState",app.getNoteTypestate(userid,bean.localId));
					jsonArray.put(object);
				}
				jsonObject.put("TbUserDetailListType", jsonArray);
				HttpUtils httpUtils = new HttpUtils(10000);
				RequestParams params = new RequestParams();
				params.addBodyParameter("data", jsonObject.toString());
				httpUtils.send(HttpMethod.POST, URLConstants.清单分类同步, params,
						new RequestCallBack<String>() {

							@Override
							public void onFailure(HttpException e, String msg) {
								Log.e("TAG", "清单分类同步失败" + msg);
							}

							@Override
							public void onSuccess(ResponseInfo<String> responseInfo) {
								for (NoteTypeBean.ListBean listBean : listBeanList){
									App.getDBcApplication().updateNoteTypeState(listBean.localId,0);
								}
							}
						});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}
